package com.happyscan138.makefun.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.happyscan138.makefun.BaseAdapter.main_new_listview;
import com.happyscan138.makefun.R;
import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.adapter.main_new_adapter;
import com.happyscan138.makefun.base.LoadListView;
import com.happyscan138.makefun.base.WaitNetDataPop;
import com.happyscan138.makefun.questionDetailed;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static android.content.Context.MODE_PRIVATE;
import static com.happyscan138.makefun.base.http.client;
import static com.happyscan138.makefun.base.http.params;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/11/24.
 */

public class main_new_Fragment extends Fragment implements LoadListView.IloadListener {
    private LoadListView listView_main_new;

    //定义一个动态数组
    private List<String> bannerId;
    private List<main_new_listview> listData;
    //声明一个SharedPreferences对象和一个Editor对象
    private SharedPreferences preferences;
    private String access_key;
    private String url;
    private Intent intent;
    private main_new_listview data;
    private int  PROBLEM_ID_INDEX ;
    private int PAGE_LENGTH;
    private main_new_adapter adapter;
    private Banner banner;
    private SwipeRefreshLayout mSwipeLayout;
    private Handler handler;
    private WaitNetDataPop waitNetDataPop;
    private ArrayList<Integer> ID;
    //Tab用来标记集合第一个元素，是否发生变化，用来做下拉刷新
    private int Tab;
    private int IfRefresh;
    private EditText SerchText;
    private ImageView Serch;
    private String KeyWord;



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_new_fragment, null);
        //s设置banner适配器
        client = new AsyncHttpClient();
        params = new RequestParams();
        preferences = getActivity().getSharedPreferences("UserInfo", MODE_PRIVATE);
        access_key = preferences.getString("UserId", "");
        //获取preferences和editor对象
        waitNetDataPop=new WaitNetDataPop(getActivity());
        waitNetDataPop.displayPop();
        ID=new ArrayList<Integer>();
        initView(view);
        getNetData();
        getAdapterView();
        listView_main_new.setInterface(this);
        return view;
    }

    public void initView(View view) {
        MyTextWatcherLisnter myTextWatcherLisnter=new MyTextWatcherLisnter();
        listView_main_new = (LoadListView) view.findViewById(R.id.listview_main_new);
        banner=(Banner) view.findViewById(R.id.banner);
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        SerchText=(EditText)view.findViewById(R.id.serchText);
        SerchText.addTextChangedListener(myTextWatcherLisnter);
        log.e("inputText",KeyWord);
        Serch=(ImageView)view.findViewById(R.id.serch);
        Serch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listData.clear();
                waitNetDataPop.displayPop();
                params=new RequestParams();
                params.put("key_word",KeyWord);
                params.put("page_count",10);
                params.put("page",1);
                log.e("params",params.toString());

                client.post(Urls.QuestionSerch,params,new JsonHttpResponseHandler(){
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        log.e("onSuccess",response.toString());
                        String jsonStr=response.toString();
                        try {
                            JSONObject jsonObject=new JSONObject(jsonStr);
                            JSONArray jsonArray=jsonObject.getJSONArray("data");
                            log.e("onSuccess",jsonArray.toString());

                            for (int i=0;i<jsonArray.length();i++) {
                                JSONObject objectData = jsonArray.getJSONObject(0);
                                if(objectData==null){
                                    Toast.makeText(getContext(),"搜索内容为空，请重新输入关键字",Toast.LENGTH_SHORT).show();
                                }else {

                                    PROBLEM_ID_INDEX = objectData.getInt("problem_id");
                                    ID.add(PROBLEM_ID_INDEX);
                                    Tab = ID.get(0);
                                    data = new main_new_listview();
                                    data.userID = objectData.getString("user_id");
                                    data.icon = Urls.base + objectData.getString("img_path");
                                    data.name = objectData.getString("nick_name");
                                    data.time = objectData.getString("create_date");
                                    data.text = objectData.getString("content");
                                    data.resource = Urls.base + objectData.getString("resource");
                                    data.Thumb = Urls.base + objectData.getString("thumb");
                                    data.m3u8 = Urls.base + objectData.getString("m3u8_file");
                                    data.viewNum = objectData.getInt("read_count");
                                    data.answerNum = objectData.getInt("replay_count");
                                    data.commentNum = i;
                                    data.goodNum = objectData.getInt("admire_count");
                                    data.problem_id = objectData.getString("problem_id");
                                    listData.add(data);

                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        adapter.notifyDataSetChanged();
                        log.e("listdatamainnew",adapter.toString());
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                        log.e("onSuccess",responseString);
                    }
                });

                waitNetDataPop.dismiss();

                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.id_swipe_ly);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                    params.put("page_count", "10");
                    params.put("problem_id_index", 0);
                    params.put("is_sao_bo", "0");
                    RequestHandle handle = client.post(Urls.cteatQuestionNew, params, new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            String jsonStr = response.toString();
                            try {
                                JSONObject jsonObject = new JSONObject(jsonStr);
                                JSONArray jsonArray = jsonObject.getJSONArray("data");
                                JSONObject obj=jsonArray.getJSONObject(0);
                                IfRefresh=obj.getInt("problem_id");
                                if (IfRefresh == Tab) {
                                    Toast.makeText(getActivity(), "已是最新数据", Toast.LENGTH_SHORT).show();
                                }    else {
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject objectData = jsonArray.getJSONObject(i);
                                        PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                        ID.add(PROBLEM_ID_INDEX);
                                        data = new main_new_listview();
                                        data.userID = objectData.getString("user_id");
                                        log.e("user_id", data.userID + "");
                                        data.icon = Urls.base + objectData.getString("img_path");
                                        log.e("icon", data.icon.toString());
                                        data.name = objectData.getString("nick_name");
                                        data.time = objectData.getString("create_date");
                                        data.text = objectData.getString("content");
                                        data.Thumb=Urls.base+objectData.getString("thumb");
                                        data.resource = Urls.base + objectData.getString("resource");
                                        data.m3u8=Urls.base+objectData.getString("m3u8_file");
                                        data.viewNum = objectData.getInt("read_count");
                                        data.answerNum = objectData.getInt("replay_count");
                                        data.commentNum = i;
                                        data.goodNum = objectData.getInt("admire_count");
                                        data.problem_id = objectData.getString("problem_id");
                                        listData.add(data);
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            adapter.notifyDataSetChanged();
                        }
                    });
                mSwipeLayout.setRefreshing(false);
            }
        });


    }

    public void getAdapterView() {
        params.put("page_count", "10");
        params.put("problem_id_index", 0);
        params.put("is_sao_bo", "0");

        RequestHandle handle = client.post(Urls.cteatQuestionNew, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String jsonStr = response.toString();
                log.e("jsonStr", jsonStr);
                listData = new ArrayList<>();
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    PAGE_LENGTH = jsonArray.length();
                    for (int i = 0; i < PAGE_LENGTH; i++) {
                        JSONObject objectData = jsonArray.getJSONObject(i);
                        PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                        ID.add(PROBLEM_ID_INDEX);
                        Tab=ID.get(0);
                        data = new main_new_listview();
                        data.userID = objectData.getString("user_id");
                        data.icon = Urls.base + objectData.getString("img_path");
                        data.name = objectData.getString("nick_name");
                        data.time = objectData.getString("create_date");
                        data.text = objectData.getString("content");
                        data.resource = Urls.base + objectData.getString("resource");
                        data.Thumb=Urls.base+objectData.getString("thumb");
                        data.m3u8=Urls.base+objectData.getString("m3u8_file");
                        data.viewNum = objectData.getInt("read_count");
                        data.answerNum = objectData.getInt("replay_count");
                        data.commentNum = i;
                        data.goodNum = objectData.getInt("admire_count");
                        data.problem_id = objectData.getString("problem_id");
                        listData.add(data);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter = new main_new_adapter(getActivity(), listData, access_key, listView_main_new);
                log.e("listdatamainnew",adapter.toString());
                listView_main_new.setAdapter(adapter);
                waitNetDataPop.dismiss();
                listView_main_new.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        intent = new Intent();
                        data = listData.get(position);
                        intent.putExtra("problem_id", data.problem_id);
                        intent.setClass(getActivity(), questionDetailed.class);
                        startActivity(intent);
                    }
                });
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                log.e("responseString", responseString);
                Toast.makeText(getActivity(), "网络好像出了点问题呢", Toast.LENGTH_LONG).show();
            }
        });
    }

    //banner获取网络数据
    private void getNetData() {

        client = new AsyncHttpClient();
        params = new RequestParams();
        RequestHandle handle = client.post(Urls.Banana, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String jsonStr = response.toString();
                bannerId=new ArrayList<String>();
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject data = jsonArray.getJSONObject(i);
                        url = Urls.base + data.getString("img_path");
                        bannerId.add(url);
                        banner.setImages(bannerId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });

    }

    @Override
    public void onLoad() {
        handler = new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                params.put("page_count", "10");
                params.put("problem_id_index", ID.get(ID.size()-1));
                params.put("is_sao_bo", "0");
                log.e("params",params.toString());
                RequestHandle handle = client.post(Urls.cteatQuestionNew, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            PAGE_LENGTH = jsonArray.length();
                            for (int i = 0; i < PAGE_LENGTH; i++) {
                                JSONObject objectData = jsonArray.getJSONObject(i);
                                PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                ID.add(PROBLEM_ID_INDEX);
                                data = new main_new_listview();
                                data.userID = objectData.getString("user_id");
                                data.icon = Urls.base + objectData.getString("img_path");
                                data.name = objectData.getString("nick_name");
                                data.time = objectData.getString("create_date");
                                data.text = objectData.getString("content");
                                data.resource = Urls.base + objectData.getString("resource");
                                data.Thumb=Urls.base+objectData.getString("thumb");
                                data.m3u8=Urls.base+objectData.getString("m3u8_file");
                                data.viewNum = objectData.getInt("read_count");
                                data.answerNum = objectData.getInt("replay_count");
                                data.commentNum = i;
                                data.goodNum = objectData.getInt("admire_count");
                                data.problem_id = objectData.getString("problem_id");
                                listData.add(data);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                listView_main_new.loadComplete();
            }
        },1000);
    }
    public class MyTextWatcherLisnter implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            KeyWord=SerchText.getText().toString();

        }
    }
}